<?php

namespace app\api\controller;

use app\admin\model\Article AS ArticleMdl;
use app\admin\model\Articlecomment;
use app\admin\model\Articlelike;
use app\admin\model\Member;
use app\admin\model\Operator;
use app\admin\model\Area;

class Article extends BaseController
{

    /**
     * 文章列表
     */
    public function getArticle()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;
        if (empty($param->villageId)) {
            // return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId不能为空');
        }
        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '分类(type) 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            //'townId' => $param->townId,
            'type' => $param->type
        ];
        if (!empty($param->typeId)) {
            $where['typeId'] = $param->typeId;
        } else {
            // 默认是首页推荐
            $where['isRecommend'] = 1;
        }
        // 根据关键字搜索
        if(!empty($param->title)) {
            $where['title'] = ['like', '%'.$param->title.'%'];
        }

        $xianId = Area::where('id', $param->townId)->value('parentId');
        $cityId = Area::where('id', $xianId)->value('parentId');
        if(!empty($param->villageId)) {
            //$where['villageId'] = $param->villageId;
            // 同一个镇/县/市的文章
            $whereStr = "((level = 1 and cityId = {$cityId}) OR (level = 2 and xianId = {$xianId}) OR (level = 3 and townId = {$param->townId}) OR (level = 4 and villageId = '{$param->villageId}'))";

            $article = ArticleMdl::where($where)->where($whereStr)->group('title')->order('villageId DESC,level DESC,topTime DESC,orderNo ASC,createDate DESC')->limit($start, $length)->select();
            $total = ArticleMdl::where($where)->where($whereStr)->count();
        } else {
            //$where['townId'] = $param->townId;
            // 同一个县/市的文章
            $whereStr = '((level = 1 and cityId = '.$cityId.') OR (level = 2 and xianId = '.$xianId.') OR (townId = '.$param->townId.'))';

            $article = ArticleMdl::where($where)->where($whereStr)->group('title')->order('level DESC,topTime DESC,orderNo ASC,createDate DESC')->limit($start, $length)->select();
            $total = ArticleMdl::where($where)->where($whereStr)->count();
        }

        // 组装operator数组，查找发布文章人所属组织，避免循环查询
        $operatorMap = Operator::getAllOrganization($param->townId);
        if (empty($article)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到文章信息');
        }

        foreach ($article as $key => $item) {
            $is_praise = Articlelike::where(['articleId'=>$item['id'],'userId'=>$param->userId])->find();
            $article[$key]['is_praise'] = $is_praise ? 'true' : 'false';
            $article[$key]['articletypeName'] = $item['typeId'];
            if($item['iconUrl']){
                $article[$key]['iconUrl'] = $item['iconUrl'].'?imageView2/1/w/330/h/220';
            }
            $article[$key]['organization'] = isset($operatorMap[$item['createOper']]) ? $operatorMap[$item['createOper']][0] : $this->defaultOrganization;
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $article, $total);
    }

    /**
     * 文章详情
     */
    public function getArticleDetail()
    {
        $param = self::getHttpParam();
        if (empty($param->articleId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'articleId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }

        $articleId = $param->articleId;
        $article = ArticleMdl::where('id', $param->articleId)->find();
        if (empty($article)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到文章信息');
        }

        // 是否已收藏
        $collectWhere = [
            'userId' => $param->userId,
            'collectId' => $articleId,
            'type' => 1
        ];
        $collectInfo = action('api/Common/getCollectInfo', ['where' => $collectWhere]);
        $isCollect = 2;
        if($collectInfo){
            $isCollect = 1;
        }
        $article['isCollect'] = $isCollect;
        $article['readCount'] += 1;

        // 每查看一次，阅读数量加1
        ArticleMdl::where('id', $param->articleId)->setInc('readCount');

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $article);
    }

    // 便民服务，获取type为work的列表，返回格式以类为主体
    public function getWorkList()
    {
        $param = self::getHttpParam();
        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId不能为空');
        }

        $xianId = Area::where('id',$param->townId)->value('parentId');
        $cityId = Area::where('id',$xianId)->value('parentId');
        $where = ['type'=>'work'];
        if(!empty($param->villageId)) {
            $where['villageId'] = $param->villageId;
            $whereStr = '((level = 1 and cityId = '.$cityId.') OR (level = 2 and xianId = '.$xianId.') OR (level = 3 and townId = '.$param->townId.'))';
        } else {
            $where['townId'] = $param->townId;
            $whereStr = '((level = 1 and cityId = '.$cityId.') OR (level = 2 and xianId = '.$xianId.'))';
        }
        
        $article1 = ArticleMdl::where(['type' => 'work'])->where($whereStr)->order('orderNo ASC')->select();
        $article = ArticleMdl::where($where)->order('orderNo ASC')->select();
        $article = array_merge($article,$article1);

        $tmp = [];
        foreach ($article as $k => $a) {
            $article[$k]['iconUrl'] = $a['iconUrl'].'?imageView2/1/w/65/h/65';
            $tmp[$a['typeId']][] = $article[$k];
        }
        $result = [];
        foreach ($tmp as $type => $data) {
            $result[] = [
                'type' => $type,
                'data' => $data
            ];
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

}